package cn.xxstudy.blog.controller.admin

import cn.xxstudy.blog.bean.Img
import cn.xxstudy.blog.util.logger
import cn.xxstudy.blog.util.saveFile
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.multipart.MultipartFile
import java.io.File
import javax.servlet.http.HttpServletRequest

/**
 * 作者：wuxinxi on 2020/12/3
 * 包名：cn.xxstudy.blog.controller.admin
 * TODO:图片墙
 */
@Controller
@RequestMapping("/admin")
class ManagerImgWallController {
    companion object {
        private const val WALL = "admin/manager-blog-img-list"
        private const val ERROR_404 = "error/404"
    }

    @GetMapping("/imgWall")
    fun imgWall(request: HttpServletRequest, model: Model): String {
        val path = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\upload\\"
        val file = File(path)
        if (!file.exists()) {
            file.mkdirs()
            return ERROR_404
        }
        val url = "${request.requestURL.substring(0, request.requestURL.lastIndexOf("admin") - 1)}/upload/"
        val wallList = mutableListOf<Img>()
        val formats = arrayOf("jpg", "jpeg", "gif", "png", "bmp", "webp")
        file.listFiles()?.filter { pre ->
            formats.find {
                it == pre.path.substring(pre.path.lastIndexOf(".") + 1, pre.path.length)
            } != null
        }?.forEach {
            val img = Img("$url${it.path.substring(it.path.lastIndexOf("\\") + 1, it.path.length)}", it.path.substring(it.path.lastIndexOf("\\") + 1, it.path.length))
            wallList.add(img)
            logger.info(img.toString())
        }
        model.addAttribute("wallList", wallList)
        return WALL
    }

    @PostMapping("/wall")
    fun uploadImgAtWall(request: HttpServletRequest, model: Model,
                        @RequestParam(value = "local-image-file", required = false) file: MultipartFile): String {
        saveFile(ManagerImgUploadController.folder, file)
        return imgWall(request, model)
    }

}